﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;

namespace HMI_MAIN
{
    static class Program
    {
        [DllImport("user32.dll")]
        private static extern
            bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern
            bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern
            bool IsIconic(IntPtr hWnd);

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            
            string[] Args = Environment.GetCommandLineArgs();
            if (Args.Length <= 1)
            {

            }
            Process instance = RunningInstance();
            if (instance == null)
            {
                //新实例
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                 Application.Run(new HTFMain());
                 // Application.Run(new FormSplash());
            }
            else
            {
               // MessageBox.Show("已启动程序", "提示");
                HandleRunningInstance(instance);
            }
        }

        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //查找相同名的进程
            foreach (Process process in processes)
            {
                //忽略当前线程
                if (process.Id != current.Id)
                {
                    //确认相同名的进程运行位置是否相同
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回相同名进程
                        return process;
                    }
                }
            }
            //没有其它进程,返回空值
            return null;
        }

        public static void HandleRunningInstance(Process instance)
        {
           // MessageBox.Show("已经在运行！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ShowWindowAsync(instance.MainWindowHandle, 1);  //调用api函数，正常显示窗口
            SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
        }
     

    }

}
